﻿using Furion.DataEncryption;
using iemtm.WeChat.Application;
using iemtm.WeChat.Application.UserCenter;
using iemtm.WeChat.Core.Extension.Helper;
using iemtm.WeChat.Core.Managers;
using Mapster;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace iemtm.WeChat.Web.Entry.Controllers
{
    [AllowAnonymous]
    public class HomeController : Controller
    {
        private readonly ISystemService _systemService;

        /// <summary>
        /// 用户管理类
        /// </summary>
        private readonly IUserManager _userManager;

        public HomeController(ISystemService systemService, IUserManager userManager)
        {
            _systemService = systemService;
            _userManager = userManager;
        }

        /// <summary>
        /// 微信授权页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            //ViewBag.Description = _systemService.GetDescription();
            string url=WeChatHelper.GetOAuthUrl("/Home/Login");
            return Redirect(url);
            //return View();
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="code">微信授权标识</param>
        /// <returns></returns>
        public async Task<IActionResult> Login(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return Redirect("Index");
            }
            else
            {
                var WXUserInfo = await WeChatHelper.GetWxUserInfo(code);
                if (WXUserInfo != null)
                {
                    //查询用户
                    var userInfo =await _userManager.GetUserByWxOpenIdAsync(WXUserInfo.openid);
                    if (userInfo != null)
                    {
                        var output = userInfo.Adapt<LoginOutput>();
                        SetCookicAndJWT(output).Wait();
                        return Redirect("/Home/Menu");
                    }
                }
                ViewBag.WxOpenId = WXUserInfo.openid;
                ViewBag.WxHreadImg = WXUserInfo.headimgurl;
            }


            return View();
        }

        public async Task<IActionResult> CheckLogin(LoginInput input)
        {

            var loginUser = await _userManager.CheckUserAsync(input.UserCode, input.UserPwd);

            if (loginUser != null)
            {
                // 映射结果
                var output = loginUser.Adapt<LoginOutput>();

                SetCookicAndJWT(output).Wait();
                //绑定微信公众号
              
                await _userManager.BindWeChat(loginUser, input.WxOpenId, input.WxHreadImg);
                return Json(new ResultModel
                {
                    Code = 1,
                    Result = "登录成功"
                });
            }
            else
            {
                return Json(new ResultModel
                {
                    Code = 0,
                    Result = "账号或密码错误"
                });
            }

        }

       /// <summary>
       /// 设置用户登录后设置Cookic和JWT
       /// </summary>
       /// <param name="output"></param>
        private async Task<bool> SetCookicAndJWT(LoginOutput output)
        {
            bool result = true;
            try
            {
                // 生成 token
                var accessToken = output.AccessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
                {
                    { "UserId",output.Id },
                    { "Account",output.UserCode }
                });



                // 生成 刷新token
                var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken);
                output.AccessToken = refreshToken;
                output.SigninedTime = DateTime.Now;
                //创建用户身份标识
                var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                claimsIdentity.AddClaims(new List<Claim>()
                    {
                        new Claim("UserId", output.Id.ToString()),
                        new Claim("Account", output.UserCode),
                        new Claim(ClaimTypes.Name, output.UserName),

                });

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
            }catch(Exception ex)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 没有权限
        /// </summary>
        /// <returns></returns>
        public IActionResult AccessDenied()
        {
            return View();
        }

    }
}